package com.tsj.model.model.vo;

import org.apache.poi.xssf.usermodel.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author taoshujian
 * @version 1.0
 * @since 2025-10-24 10:58:05
 */
public class ExcelAttachmentExtractor2 {

    public static List<AttachmentInfo> extractAllAttachments(XSSFSheet sheet) throws IOException {
        List<AttachmentInfo> attachments = new ArrayList<>();

        // 1. 提取所有图片（关键：直接从工作表获取图片数据列表，不依赖形状类型）
        extractPictures(sheet, attachments);

        // 2. 提取所有OLE附件（如PDF等）
        extractOLEAttachments(sheet, attachments);

        return attachments;
    }

    /**
     * 提取所有图片（绕过形状类型判断，确保100%识别）
     */
    private static void extractPictures(XSSFSheet sheet, List<AttachmentInfo> attachments) {
        // 获取工作表中所有图片数据
        List<XSSFPictureData> allPictureData = sheet.getWorkbook().getAllPictures();
        if (allPictureData.isEmpty()) {
            return;
        }

        // 获取绘图容器中的所有形状，用于匹配图片位置
        XSSFDrawing drawing = sheet.getDrawingPatriarch();
        if (drawing == null) {
            return;
        }

        // 遍历所有形状，寻找图片形状并关联图片数据
        for (XSSFShape shape : drawing.getShapes()) {
            // 判断是否为图片形状（通过是否包含图片索引）
            if (shape instanceof XSSFPicture) {
                XSSFPicture picture = (XSSFPicture) shape;
                XSSFPictureData picData = picture.getPictureData(); // 直接获取图片数据（无需索引）
                if (picData == null) {
                    continue; // 过滤无效图片
                }

                // 获取图片格式
                String mimeType = picData.getMimeType();
                String format = getFormatFromMimeType(mimeType);

                // 生成文件名（无法获取原始名称，用时间戳+格式）
                String fileName = "image_" + System.currentTimeMillis() + "." + format;

                // 获取图片所在单元格
                XSSFClientAnchor anchor = picture.getClientAnchor();
                String cellAddress = getCellAddress(anchor.getRow1(), anchor.getCol1());

                // 添加到附件列表（参数顺序与构造函数一致）
                attachments.add(new AttachmentInfo(
                        fileName,
                        cellAddress,
                        "图片",
                        format,
                        picData.getData() // 字节数组，对应content参数
                ));
            }
        }
    }

    /**
     * 提取所有OLE附件（如PDF、Word等）
     */
    private static void extractOLEAttachments(XSSFSheet sheet, List<AttachmentInfo> attachments) throws IOException {
        XSSFDrawing drawing = sheet.getDrawingPatriarch();
        if (drawing == null) {
            return;
        }

        for (XSSFShape shape : drawing.getShapes()) {
            // 处理OLE对象
            if (shape instanceof XSSFObjectData) {
                XSSFObjectData oleData = (XSSFObjectData) shape;
                XSSFClientAnchor anchor = (XSSFClientAnchor) shape.getAnchor();
                String cellAddress = getCellAddress(anchor.getRow1(), anchor.getCol1());

                String fileName = oleData.getFileName();
                if (fileName == null || fileName.trim().isEmpty()) {
                    fileName = "ole_attachment_" + System.currentTimeMillis();
                }
                String format = getFormatFromFileName(fileName);

                attachments.add(new AttachmentInfo(
                        fileName,
                        cellAddress,
                        "OLE附件",
                        format,
                        oleData.getObjectData()
                ));
            }
        }
    }

    // 从MIME类型获取格式
    private static String getFormatFromMimeType(String mimeType) {
        if (mimeType == null) return "unknown";
        switch (mimeType) {
            case "image/jpeg": return "jpg";
            case "image/png": return "png";
            case "image/gif": return "gif";
            case "image/bmp": return "bmp";
            case "image/svg+xml": return "svg";
            default: return mimeType.split("/")[1];
        }
    }

    // 从文件名获取格式
    private static String getFormatFromFileName(String fileName) {
        int dotIndex = fileName.lastIndexOf(".");
        return (dotIndex > 0) ? fileName.substring(dotIndex + 1) : "bin";
    }

    // 转换单元格地址（行号、列号 → A1格式）
    private static String getCellAddress(int rowIndex, int colIndex) {
        return getColumnLetter(colIndex) + (rowIndex + 1);
    }

    // 列号转字母（0→A，26→AA）
    private static String getColumnLetter(int colIndex) {
        if (colIndex < 0) return "";
        StringBuilder sb = new StringBuilder();
        while (colIndex >= 0) {
            int remainder = colIndex % 26;
            sb.append((char) ('A' + remainder));
            colIndex = (colIndex / 26) - 1;
            if (colIndex < 0) break;
        }
        return sb.reverse().toString();
    }


}
